package com.ruoci.redis.requestlimit.file;


import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * @Author yang
 **/
public class FileTypeValidator implements ConstraintValidator<AllowedFileTypes, MultipartFile> {

    AllowedFileTypes  allowedFileTypes;
    @Override
    public void initialize(AllowedFileTypes constraintAnnotation) {
        this.allowedFileTypes = constraintAnnotation;
    }

    @Override
    public boolean isValid(MultipartFile file, ConstraintValidatorContext context) {
        if (file.getSize()<= 0 || file.isEmpty()) {
            return true;
        }
        String[] allowedTypes = allowedFileTypes.allowedFileTypes();
        String fileType = FilenameUtils.getExtension(file.getOriginalFilename());
        return  Arrays.asList(allowedTypes).contains(fileType);
    }
}
